﻿package vn.cuhanh.sys;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import vn.cuhanh.utils.HelperFunc;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;


public class Downloader {
	private Context ctx;
	private String strUrl;
	private String savePath;
	private ProgressBar progressBar;
	private Runnable successCallback;
	private Runnable failCallback;
	private boolean isDownloading;
	
	public Downloader(Context ctx, String strUrl, String savePath,
			ProgressBar progressBar, Runnable successCallback,
			Runnable failCallback) {
		super();
		this.ctx = ctx;
		this.strUrl = strUrl;
		this.savePath = savePath;
		this.progressBar = progressBar;
		this.successCallback = successCallback;
		this.failCallback = failCallback;
	}
	
	public void start() {
		if(isDownloading()) {
			return;
		}
		thread.start();
	}
	@SuppressWarnings("deprecation")
	public void stop() {
		if(!isDownloading()) {
			return;
		}
		thread.stop();
		deleteDownloadedFile();
	}
	
	private Thread thread = new Thread(new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
		        //set the download URL, a url that points to a file on the internet
		        //this is the file to be downloaded
				//"http://120.138.75.2/desktop.rar"
		        URL url = new URL(strUrl);

		        //create the new connection
		        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

		        //set up some things on the connection
		        urlConnection.setRequestMethod("GET");
		        urlConnection.setDoOutput(true);

		        //and connect!
		        urlConnection.connect();

		        //set the path where we want to save the file
		        //in this case, going to save it on the root directory of the
		        //sd card.
		        File SDCardRoot = Environment.getExternalStorageDirectory();
		        //create a new file, specifying the path, and the filename
		        //which we want to save the file as.
//		        File file = new File(SDCardRoot,"somefile.ext");
		        File file = new File(SDCardRoot, savePath);
		        //this will be used to write the downloaded data into the file we created
		        FileOutputStream fileOutput = new FileOutputStream(file);

		        //this will be used in reading the data from the internet
		        InputStream inputStream = urlConnection.getInputStream();

		        //this is the total size of the file
		        int totalSize = urlConnection.getContentLength();
		        //variable to store total downloaded bytes
		        int downloadedSize = 0;

		        //create a buffer...
		        byte[] buffer = new byte[1024];
		        int bufferLength = 0; //used to store a temporary size of the buffer
		        setDownloading(true);
		        //now, read through the input buffer and write the contents to the file
		        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
		                //add the data in the buffer to the file in the file output stream (the file on the sd card
		                fileOutput.write(buffer, 0, bufferLength);
		                //add up the size so we know how much is downloaded
		                downloadedSize += bufferLength;
		                //this is where you would do something to report the prgress, like this maybe
		                updateProgress(ctx, progressBar, downloadedSize, totalSize);
		        }
		        //close the output stream when done
		        fileOutput.close();
		        
		        if(successCallback != null) {
		        	successCallback.run();
		        }
		        return;
			//catch some possible errors...
			} catch (MalformedURLException e) {
		        HelperFunc.readStackTrace(e);
			} catch (IOException e) {
		        HelperFunc.readStackTrace(e);
			} catch (Exception e) {
				// TODO: handle exception
				HelperFunc.readStackTrace(e);
			} finally {
				setDownloading(false);
			}
			deleteDownloadedFile();
			if(failCallback != null) {
				failCallback.run();
			}
		}
	});
	
	public void updateProgress(Context ctx, final ProgressBar progressBar, final int downloadedSize, final int totalSize) {
		Log.d("progress", downloadedSize + "/" + totalSize);
		((Activity)ctx).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(progressBar != null) {
					progressBar.setMax(totalSize);
					progressBar.setProgress(downloadedSize);
					progressBar.invalidate();
				}
			}
		});
	}
	
	public void deleteDownloadedFile() {
		File SDCardRoot = Environment.getExternalStorageDirectory();
		File file = new File(SDCardRoot, savePath);
		file.delete();
	}

	public boolean isDownloading() {
		return isDownloading;
	}

	private void setDownloading(boolean isDownloading) {
		this.isDownloading = isDownloading;
	}
}